Page({
  data: {
    name: '',
    userId: '',
    password: '',
    confirmPassword: '',
    department: '',
    classId: null,
    className: '',
    phone: '',
    email: '',
    role: 'student',
    roles: [
      {value: 'student', name: '学生'},
      {value: 'teacher', name: '教师'}
    ],
    departments: [],
    departmentIndex: 0,
    classes: [],
    classesData: [],
    classIndex: 0,
    errorMsg: '',
    hasAgreed: false,
    isLoading: false
  },

  onLoad: function() {
    this.fetchDepartments();
  },

  fetchDepartments: function() {
    const app = getApp();
    const serverUrl = app.globalData.serverUrl || 'http://localhost:3000';
    
    wx.request({
      url: `${serverUrl}/api/departments`,
      method: 'GET',
      success: (res) => {
        console.log('获取到院系数据:', res.data);
        // 提取院系名称数组
        const departmentNames = res.data.map(item => item.name);
        this.setData({
          departments: departmentNames,
          departmentsData: res.data,  // 保存完整数据
          departmentIndex: 0
        });
      },
      fail: (err) => {
        console.error('获取院系失败:', err);
        wx.showToast({
          title: '获取院系数据失败',
          icon: 'none'
        });
      }
    });
  },



  roleChange: function(e) {
    const role = e.detail.value;
    this.setData({ role });
    
    if (role === 'student' && this.data.department) {
      this.fetchClasses(this.data.department);
    }
  },

  fetchClasses: function(department) {
    const app = getApp();
    const serverUrl = app.globalData.serverUrl || 'http://localhost:3000';
    
    console.log('获取班级数据，院系:', department);
    
    wx.request({
      url: `${serverUrl}/api/classes`,
      method: 'GET',
      data: { department: department },
      success: (res) => {
        console.log('获取到班级数据:', res.data);
        if (res.statusCode === 200 && res.data && res.data.length > 0) {
          this.setData({
            classesData: res.data,
            classes: res.data.map(item => item.name),
            classIndex: 0,
            classId: res.data[0].id,
            className: res.data[0].name
          });
        } else {
          console.error('班级数据为空或格式不正确:', res.data);
          wx.showToast({
            title: '获取班级数据失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        console.error('获取班级请求失败:', err);
        wx.showToast({
          title: '获取班级数据失败',
          icon: 'none'
        });
      }
    });
  },
  changeDepartmentPicker: function(e) {
    const index = parseInt(e.detail.value);
    if (this.data.departmentsData && this.data.departmentsData.length > index) {
      const selectedDepartment = this.data.departmentsData[index];
      console.log('选择院系变更:', selectedDepartment.name, '索引:', index);
      
      this.setData({
        departmentIndex: index,
        department: selectedDepartment.name
      });

      if (this.data.role === 'student') {
        this.fetchClasses(selectedDepartment.name);
      }
    }
  },

  // 添加确认院系选择方法
  confirmDepartmentPicker: function() {
    const index = this.data.departmentIndex;
    if (this.data.departmentsData && this.data.departmentsData.length > index) {
      const selectedDepartment = this.data.departmentsData[index];
      console.log('确认选择院系:', selectedDepartment.name, '索引:', index);
      
      this.setData({
        department: selectedDepartment.name,
        showDepartmentPickerView: false
      });
    } else {
      console.error('院系数据不存在');
      wx.showToast({
        title: '院系选择失败',
        icon: 'none'
      });
    }
  },

  cancelDepartmentPicker: function() {
    this.setData({
      showDepartmentPickerView: false
    });
  },

  changeClassPicker: function(e) {
    const index = parseInt(e.detail.value);
    if (this.data.classesData && this.data.classesData.length > index) {
      const selectedClass = this.data.classesData[index];
      console.log('选择班级变更:', selectedClass.name, 'ID:', selectedClass.id, '索引:', index);
      
      this.setData({
        classIndex: index,
        classId: selectedClass.id,
        className: selectedClass.name
      });
    }
  },

  confirmClassPicker: function() {
    const index = this.data.classIndex;
    if (this.data.classesData && this.data.classesData.length > index) {
      const selectedClass = this.data.classesData[index];
      
      this.setData({
        classId: selectedClass.id,
        className: selectedClass.name,
        showClassPickerView: false
      });
    }
  },

  cancelClassPicker: function() {
    this.setData({
      showClassPickerView: false
    });
  },

  showDepartmentPicker: function() {
    if (!this.data.departments || this.data.departments.length === 0) {
      wx.showToast({
        title: '正在加载院系数据',
        icon: 'none'
      });
      return;
    }
    this.setData({
      showDepartmentPickerView: true
    });
  },

  showClassPicker: function() {
    if (!this.data.classes || this.data.classes.length === 0) {
      wx.showToast({
        title: '请先选择院系',
        icon: 'none'
      });
      return;
    }
    this.setData({
      showClassPickerView: true
    });
  },

  inputName: function(e) {
    this.setData({ name: e.detail.value });
  },

  inputUserId: function(e) {
    this.setData({ userId: e.detail.value });
  },

  inputPhone: function(e) {
    this.setData({ phone: e.detail.value });
  },

  inputEmail: function(e) {
    this.setData({ email: e.detail.value });
  },

  inputPassword: function(e) {
    this.setData({ password: e.detail.value });
  },

  inputConfirmPassword: function(e) {
    this.setData({ confirmPassword: e.detail.value });
  },

  agreementChange: function(e) {
    this.setData({ hasAgreed: e.detail.value.length > 0 });
  },

  register: function() {
    if (!this.data.hasAgreed) {
      wx.showToast({
        title: '请先阅读并同意用户协议',
        icon: 'none'
      });
      return;
    }

    if (!this.data.name) {
      this.setData({ errorMsg: '请输入姓名' });
      return;
    }
    if (!this.data.userId) {
      this.setData({ errorMsg: '请输入学号/工号' });
      return;
    }
    if (!this.data.password) {
      this.setData({ errorMsg: '请输入密码' });
      return;
    }
    if (this.data.password !== this.data.confirmPassword) {
      this.setData({ errorMsg: '两次输入的密码不一致' });
      return;
    }
    if (!this.data.phone) {
      this.setData({ errorMsg: '请输入手机号' });
      return;
    }
    if (this.data.role === 'student' && !this.data.classId) {
      this.setData({ errorMsg: '请选择班级' });
      return;
    }

    this.setData({
      isLoading: true,
      errorMsg: ''
    });

    const app = getApp();
    const serverUrl = app.globalData.serverUrl || 'http://localhost:3000';

    const userData = {
      name: this.data.name,
      userId: this.data.userId,
      password: this.data.password,
      role: this.data.role,
      department: this.data.department,
      classId: this.data.role === 'student' ? this.data.classId : null,
      phone: this.data.phone,
      email: this.data.email || null
    };

    wx.request({
      url: `${serverUrl}/api/auth/register`,
      method: 'POST',
      data: userData,
      success: (res) => {
        if (res.statusCode === 201) {
          wx.showToast({
            title: '注册成功',
            icon: 'success'
          });
          setTimeout(() => {
            wx.navigateBack();
          }, 1500);
        } else {
          this.setData({
            errorMsg: res.data.message || '注册失败，请稍后再试'
          });
        }
      },
      fail: (err) => {
        console.error('注册请求失败:', err);
        this.setData({
          errorMsg: '网络错误，请稍后再试'
        });
      },
      complete: () => {
        this.setData({ isLoading: false });
      }
    });
  },

  navigateToAgreement: function() {
    wx.navigateTo({
      url: '/pages/shezhi/agreement/agreement'
    });
  },

  navigateToPrivacy: function() {
    wx.navigateTo({
      url: '/pages/shezhi/privacy/privacy'
    });
  },

  goToLogin: function() {
    wx.navigateBack();
  }
});